package com.container.core;

import com.container.request.HttpRequestInputStream;
import com.container.request.NettyHttpServletRequest;
import com.container.response.NettyHttpServletResponse;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;

public class ChannelReadHandler extends ChannelInboundHandlerAdapter {
    private MyServletContext servletContext;
    private HttpRequestInputStream inputStream;

    ChannelReadHandler(MyServletContext servletContext) {
        this.servletContext = servletContext;
    }

    public MyServletContext getServletContext() {
        return servletContext;
    }

    public HttpRequestInputStream getInputStream() {
        return inputStream;
    }

    //channel激活时，开启一个新的输入流
    @Override
    public void channelActive(ChannelHandlerContext context) throws Exception {
        inputStream = new HttpRequestInputStream(context.channel());
    }

    //有数据进入时，执行读操作
    @Override
    public void channelRead(ChannelHandlerContext context, Object msg) throws Exception {
        if (msg instanceof HttpRequest) {
            HttpRequest request = (HttpRequest) msg;
            HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, false);
            HttpUtil.setKeepAlive(response, HttpUtil.isKeepAlive(request));

            //封装request和response对象
            NettyHttpServletResponse servletResponse = new NettyHttpServletResponse(context, servletContext, response);
            NettyHttpServletRequest servletRequest = new NettyHttpServletRequest(context, this, request, servletResponse);
            servletResponse.setRequest(servletRequest);

            if (HttpUtil.is100ContinueExpected(request)) { //请求头包含Expect: 100-continue
                context.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE), context.voidPromise());
            }
            context.fireChannelRead(servletRequest);
        }

        if (msg instanceof HttpContent) {
            inputStream.addContent((HttpContent) msg);
        }
    }

    //读完毕，等待下一次连接
    @Override
    public void channelInactive(ChannelHandlerContext context) throws Exception {
        inputStream.close();
    }
}